import { OssConfigModel, OssCredentialsModel, OssPolicyModel } from '../../core/api/models/oss-config-model';
import { ossConfigService } from '../../core/api/request/oss-config-service';

let sequence = 100;

// 缓存oss
let OSS_CONFIG: OssConfigModel | null = null;

const BASE_CONFIG = {
    region: "",
    //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用STS方式来进行API访问
    bucket: "",
    objectKeyPrefix: "",
    endpoint: ""
}

export const OssController = {
    getOssCredentials: async function (): Promise<OssCredentialsModel> {
        const ossConfig = await getOssConfig();
        return Object.assign(ossConfig.assumeRoleResponse.credentials);
    },

    getOssBaseConfig: async function () {
        const ossConfig = await getOssConfig();
        BASE_CONFIG.region = ossConfig.region
        BASE_CONFIG.bucket = ossConfig.bucket
        BASE_CONFIG.objectKeyPrefix = ossConfig.basedir;
        BASE_CONFIG.endpoint = ossConfig.endpoint;
        return BASE_CONFIG;
    },
    getOssPolicyConfig: async function (param: any) {
        
        return ossConfigService.getPolicy(param);
    },

    createObjectKey: async (fileName: string,policyModel: OssPolicyModel) => {
        let fileType = '';
        let startIndex = fileName.lastIndexOf(".");
        if (startIndex != -1) {
            fileType = fileName.substring(startIndex + 1, fileName.length).toLowerCase();
        }
        return `${policyModel.dir}/${policyModel.fileNamePrefix}.${fileType || 'jpg'}`;
    }
}

async function getOssConfig() {
    // 预留3分钟时间提前判断过期以访临界情况
    if (!OSS_CONFIG || (new Date(OSS_CONFIG.assumeRoleResponse.credentials.expiration).getTime() < Date.now())) {
        OSS_CONFIG = await ossConfigService.getToken();
    }
    return OSS_CONFIG;
}

 